package pfc.aviloc.comunicacion;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.xml.sax.InputSource;

import android.util.Log;




public class Comunicacion {
	
	private static HttpClient httpclient = null;
	
//	public static void inicializarComunicacion() {
//		int TIMEOUT_MILLISEC = 60001; // =10sec
//		HttpParams my_httpParams = new BasicHttpParams();
//		HttpConnectionParams.setConnectionTimeout(my_httpParams, TIMEOUT_MILLISEC);
//		HttpConnectionParams.setSoTimeout(my_httpParams, TIMEOUT_MILLISEC);
//		httpclient = new DefaultHttpClient(my_httpParams);
//		// httpclient = new DefaultHttpClient();
//	}
	public static void inicializarComunicacion(int timeOut) {
		int TIMEOUT_MILLISEC = timeOut; // =10sec
		HttpParams my_httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(my_httpParams, TIMEOUT_MILLISEC);
		HttpConnectionParams.setSoTimeout(my_httpParams, TIMEOUT_MILLISEC);
		httpclient = new DefaultHttpClient(my_httpParams);
		// httpclient = new DefaultHttpClient();
	}
	
	public static boolean doPing(String urlString, int timeOut) throws IOException {
		boolean respuesta = false;
		int response = -1;
		URL url = new URL(urlString);
		URLConnection conn = url.openConnection();
		if (!(conn instanceof HttpURLConnection)) {
			throw new IOException("Not an HTTP connection");
		}
		try {
			HttpURLConnection httpConn = (HttpURLConnection) conn;
			httpConn.setAllowUserInteraction(false);
			httpConn.setInstanceFollowRedirects(true);
			httpConn.setRequestMethod("GET");
			httpConn.setConnectTimeout(timeOut);
			httpConn.connect();
			response = httpConn.getResponseCode();
			if (response == HttpURLConnection.HTTP_OK) {
				respuesta = true;
			}
		} catch (Exception ex) {
			respuesta = false;
			ex.printStackTrace();
		}
		return respuesta;
	}

	public static String getMensajeRegistro(String url,Map<String, String> kvParameters, int longMaxRespuesta) throws ClientProtocolException,IOException {
		//Log.i("INFO", "----------->> getMensageRegistro: url="+url);
		HttpPost httpPost = new HttpPost(url);
		//Log.i("INFO", "----------->> getMensageRegistro: httpPost="+httpPost);
		if ((kvParameters != null && kvParameters.isEmpty() == false)) {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
					kvParameters.size());
			String k, v;
			Iterator<String> itKeys = kvParameters.keySet().iterator();
			while (itKeys.hasNext()) {
				k = itKeys.next();
				v = kvParameters.get(k);
				nameValuePairs.add(new BasicNameValuePair(k, v));
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		}

		HttpResponse response;
		response = httpclient.execute(httpPost);
		InputStream resIS = response.getEntity().getContent();
		byte[] arrayMensaje = new byte[longMaxRespuesta];
		resIS.read(arrayMensaje);
		String mensajeString = (new String(arrayMensaje)).trim();
		//Log.i("INFO", "----------->> getMensageRegistro: mensajeString="+mensajeString);
		return mensajeString;
	}
	 
	public static InputSource getXML(String url, Map<String, String> kvParameters) {
		InputSource xmlInputSource = null;
		try {
			HttpPost httpPost = new HttpPost(url);
			if ((kvParameters != null && kvParameters.isEmpty() == false)) {
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
						kvParameters.size());
				String k, v;
				Iterator<String> itKeys = kvParameters.keySet().iterator();
				while (itKeys.hasNext()) {
					k = itKeys.next();
					v = kvParameters.get(k);
					nameValuePairs.add(new BasicNameValuePair(k, v));
				}
				httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			}
			//Log.i("INFO", "----> URL="+url);
			//Log.i("INFO", "----> kvParameters="+kvParameters);
			
			HttpResponse response = httpclient.execute(httpPost);
			HttpEntity responseEntity = response.getEntity();
			String responseString = EntityUtils.toString(responseEntity);
			
			Log.i("INFO", "----> RESPUESTA="+responseString);
			
			StringReader responseSR = new StringReader(responseString);
			xmlInputSource = new InputSource(responseSR);
			//InputStream responseIS = responseEntity.getContent();
			//xmlInputSource = new InputSource(responseIS);
			
//			InputStreamReader inReader = new InputStreamReader(responseIS);
//			BufferedReader bufferReader = new BufferedReader(inReader);			
//			String linea;
//			String xmlString = "";
//			Log.i("BUFFER", "--> ********************************************");
//			int tam=0;
//			boolean salir = true;
//			while (salir) {
//				linea = bufferReader.readLine();
//				if (linea == null) {
//					salir = false;
//				}else {
//					xmlString = xmlString+linea;
//					tam=tam+linea.length();
//				}
//				Log.i("BUFFER", "-->" + linea);
//			}
//			bufferReader.close();
//			Log.i("BUFFER", "--> ********************************************");
//			StringReader xmlReader= new StringReader(xmlString);
//			BufferedReader bufferReader2 = new BufferedReader(xmlReader);				
//			//InputSource xml = new InputSource(in);	
//			//InputSource xml = new InputSource(bufferReader);	
//			InputSource xml = new InputSource(bufferReader2);	
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return xmlInputSource;
	}
	
	
//	public static HttpResponse getXML(String url) throws ClientProtocolException, IOException{
//		HttpPost httpPost = new HttpPost(url);
//		HttpResponse response;
//		response = httpclient.execute(httpPost);
//		//HttpResponse response = httpclient.execute(httpPost);
//		return response;
//	}
	
//**************************
//**************************
//	public static HttpResponse doPost(String url, Map<String, String> kvParameters) throws ClientProtocolException,IOException {
//		HttpPost httppost = new HttpPost(url);
//
//		if ((kvParameters != null && kvParameters.isEmpty() == false)) {
//			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(kvParameters.size());
//			String k, v;
//			Iterator<String> itKeys = kvParameters.keySet().iterator();
//			while (itKeys.hasNext()) {
//				k = itKeys.next();
//				v = kvParameters.get(k);
//				nameValuePairs.add(new BasicNameValuePair(k, v));
//			}
//
//			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//		}
//		HttpResponse response;
//		response = httpclient.execute(httppost);
//		response.getAllHeaders();
//		
//		return response;
//	}
//	
//	
//	public static HttpResponse doPostMando(String url, Map<String, String> kvParameters) throws ClientProtocolException, IOException {
//		HttpClient httpclient =  new DefaultHttpClient();
//		HttpPost httppost = new HttpPost(url);
//
//		if ((kvParameters != null && kvParameters.isEmpty() == false)) {
//			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
//					kvParameters.size());
//			String k, v;
//			Iterator<String> itKeys = kvParameters.keySet().iterator();
//			while (itKeys.hasNext()) {
//				k = itKeys.next();
//				v = kvParameters.get(k);
//				nameValuePairs.add(new BasicNameValuePair(k, v));
//			}
//
//			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//		}
//		HttpResponse response;
//		response = httpclient.execute(httppost);
//
//		return response;
//	}
//	
//	
//	public static Boolean doPing(String urlString) throws IOException {
//		Boolean respuesta= false;
//		int response = -1;
//
//		URL url = new URL(urlString);
//		URLConnection conn = url.openConnection();
//
//		if (!(conn instanceof HttpURLConnection)) {
//			throw new IOException("Not an HTTP connection");
//		}
//		
//		try {
//			HttpURLConnection httpConn = (HttpURLConnection) conn;
//			httpConn.setAllowUserInteraction(false);
//			httpConn.setInstanceFollowRedirects(true);
//			httpConn.setRequestMethod("GET");
//			httpConn.setConnectTimeout(3000);
//			httpConn.connect();
//			response = httpConn.getResponseCode();
//			if (response == HttpURLConnection.HTTP_OK) {
//				respuesta = true;
//			}
//		} catch (Exception ex) {
//			respuesta=false;
//			ex.printStackTrace();
//		}
//
//		return respuesta;
//	}
//		
//
//	public static Bitmap DownloadImage(String URL) {
//		Bitmap bitmap = null;
//		InputStream in = null;
//		try {
//			HttpResponse res = Comunicacion.doGet(URL);
//			in = res.getEntity().getContent();
//			bitmap = BitmapFactory.decodeStream(in);
//			in.close();
//		} catch (IOException e1) {
//			e1.printStackTrace();
//		}
//		return bitmap;
//	}
//		
//	
//	public static HttpResponse doPost(String url) throws ClientProtocolException, IOException {
//		
//		HttpClient httpclient = new DefaultHttpClient();
//		HttpPost httppost = new HttpPost(url);
//		HttpResponse response;
//		response = httpclient.execute(httppost);
//	
//		return response;
//	}
//	
//	
//	public static HttpResponse doGet(String url) throws ClientProtocolException, IOException {
//
//		HttpGet httpget = new HttpGet(url);
//		HttpResponse response = httpclient.execute(httpget);
//	
//		return response;
//	}
	
}
